package com.kangfu.api.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teautil.models.RuntimeOptions;
import com.kangfu.api.service.IAliyunSmsService;
import com.kangfu.common.constant.AliyunConstant;
import com.kangfu.common.utils.RedisUtils;
import com.kangfu.wechat.api.TokenApi;
import com.kangfu.wechat.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import com.aliyun.teautil.*;

import java.util.HashMap;

@Service
public class AliyunSmsServiceImpl implements IAliyunSmsService {

    private static final Logger logger = LoggerFactory.getLogger(AliyunSmsServiceImpl.class);

    @Autowired
    public RedisUtils redisUtils;

    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = AliyunConstant.ENDPOINT;
        return new Client(config);
    }

    @Override
    public boolean sendSMS(String phoneNumber, String code) {
        try {
            Client client = createClient(AliyunConstant.ACCESS_KEY_ID, AliyunConstant.ACCESS_KEY_SECRET);
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(phoneNumber);
            sendSmsRequest.setSignName(AliyunConstant.SIGN_NAME);
            sendSmsRequest.setTemplateCode(AliyunConstant.TEMPLATE_CODE);

            HashMap<String, String> codeMap = new HashMap<>();
            codeMap.put("code",code);

            sendSmsRequest.setTemplateParam(JsonUtil.toJSONString(codeMap));
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if (sendSmsResponse.getBody() != null && sendSmsResponse.getBody().getCode() != null && "OK".equals(sendSmsResponse.getBody().getCode())) {
                //发送成功
                //把code存入redis
                redisUtils.set("change_phone:"+phoneNumber,code,300L);
                return true;
            }
            return false;
        } catch (TeaException error) {
            // 如有需要，请打印 error
            System.out.println(error.message);
            logger.error("短信发送失败：===" + error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            System.out.println(error.message);
            logger.error("短信发送失败：===" + error.message);
        }
        return false;
    }

}
